package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("updatePas")
public class UpdatePasswordController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("updatepage")
    public String updatepage () {
        return "common/updatePwd";
    }

    @RequestMapping("updatePassword")
    @ResponseBody
    public JsonResult updatePassword (String oldPassword, String newPassword) {
        //通过token获取用户名
        Object username = SecurityUtils.getSubject().getPrincipal();
        //判断是否存在数据库
        Employee employee = employeeService.selectByName((String) username);

        //对旧密码加密,将用户名当做盐
        Md5Hash md5HashOldPwd = new Md5Hash(oldPassword,employee.getName());

        //如果从数据库获取到的密码跟旧密码加密后的密码相同
        if (employee.getPassword().equals(md5HashOldPwd.toString())) {
            //那么将从前台获取到的新密码加密
            Md5Hash md5HashNewPwd = new Md5Hash(newPassword, employee.getName());
            //更新数据库
            employeeService.updateNewPassword(employee.getId(), md5HashNewPwd.toString());
           // session.invalidate();

            return new JsonResult();
        } else {
            return new JsonResult(false, "原密码错误");

        }

    }

}
